package com.dongrj.framework.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.dongrj.framework.core.utils.StringUtils;

import java.util.function.Function;

public abstract class AbstractConverter<T> implements Converter<T> {

    public abstract Function<T, String> source();

    public String valueNull() {
        return "";
    }

    public String convertFail(T from) {
        return "";
    }

    @Override
    public WriteCellData<String> convertToExcelData(T value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        if (value == null) {
            return new WriteCellData<>(valueNull());
        }
        Function<T, String> source = source();
        if (source == null) {
            return new WriteCellData<>(convertFail(value));
        }
        String apply = source.apply(value);
        if (StringUtils.isEmpty(apply)) {
            return new WriteCellData<>(convertFail(value));
        }
        return new WriteCellData<>(apply);
    }
}
